from time import sleep
import DrissionPage.errors
from DrissionPage import WebPage
from DrissionPage import ChromiumOptions
from DrissionPage import SessionPage


'''
不可行
get user info --> check login must get token --> set token in header to get other information

还是老老实实监听数据包吧。。。。
https://ywtb.cuit.edu.cn/third_api/cxek/PhoneApi/api/Account/Login?code=123&state=GZState
'''


def header_init(page: WebPage) -> dict:
    token = page.session_storage('token')
    if token is None:
        token = get_token(page)
    header = {
        'user-agent': page._headers.get('user-agent'),
        'authorization': 'Bearer ' + token
    }
    return header

def stats_score(home_page: WebPage):
    req = SessionPage(session_or_options=home_page.session)
    header = header_init(home_page)
    req.set.headers(headers=header)
    req.get('https://ywtb.cuit.edu.cn/third_api/cxek/PhoneApi/api/Graduation/GetStuDetail?studentId=' + username + '&yearValue=')
    data = req.json
    print('总分： ' + data['Info']['SumGetNum'])
    for type in data['TypeList']:
        print('\t', type['CurriculumName'], ' : ', type['SumScore'])


def login(page: WebPage) -> bool:
    try:
        input_area = page.eles('@class=el-input__inner')
        login_btn = page.ele('@@tag()=button@@text()=登 录')
    except DrissionPage.errors.ElementNotFoundError:
        print('登录时：元素获取失败')
    input_area[0].input(username)
    input_area[1].input(password)
    login_btn.click()
    success = page.wait.url_change('https://ywtb.cuit.edu.cn/#/homePage')
    return success


def enter_second_class_system(page: WebPage):
    home_tab = page.get_tab(url='ywtb.cuit.edu.cn/#/homePage', title='成都信息工程大学')
    second_class = home_tab.ele('@@class=app-name@@text()=第二课堂移动端')
    second_class.click()



def get_token(page: WebPage):
    enter_second_class_system(page)
    sleep(2)
    tab = page.get_tab(url='https://ywtb.cuit.edu.cn/file/apps')    #https://ywtb.cuit.edu.cn/file/apps/cxek/index.html?code=123&state=GZState#/
    tab.listen.set_targets(targets='.*Login', method='POST', is_regex=True)
    tab.listen.start()
    tab.refresh()
    res = tab.listen.wait(1, 5)
    if type(res) is bool:
        print('获取数据包(Login)时：超时')
    tab.listen.stop()
    return res.response.body["access_token"]


if __name__ == '__main__':
    username = input('输入账号： ')
    password = input('输入密码： ')
    opt = ChromiumOptions().headless()
    page = WebPage(chromium_options=opt)

    page.get(url='https://ywtb.cuit.edu.cn/#/homePage')
    has_change = page.wait.url_change(text='https://ywtb.cuit.edu.cn/#/login', timeout=3)
    login_success = True
    if has_change:
        login_success = login(page)

    if login_success:
        print('登录成功')
        stats_score(page)
    else:
        print('登录时：用户名或密码错误')
    page.close()
